package com.itheima.controller.system.dept;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.Company;
import com.itheima.domain.Course;
import com.itheima.domain.Dept;
import com.itheima.utils.BeanUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet("/system/dept/*")
public class DeptServlet extends BaseServlet {
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        // 获取当前页码和每页条目数
        String page = req.getParameter("page");
        String pageSize = req.getParameter("pageSize");
        //调用业务层方法
     List<Dept> deptList=deptService.findAll(page,pageSize);
        PageInfo<Dept> deptPageInfo = new PageInfo<>(deptList);
        req.getSession().setAttribute("page",deptPageInfo);


        req.getRequestDispatcher("/pages/system/dept/list.jsp").forward(req,resp);

    }


    private void dlpage(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        List<Dept> deptList=deptService.findAlldept();

        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(deptList);

        resp.getWriter().write(s);
    }


    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Dept dept = BeanUtil.fillBean(req, Dept.class);

        deptService.save(dept);

        findAll(req,resp);
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String id = req.getParameter("id");
        Dept dept = deptService.edit(id);
        req.getSession().setAttribute("dept",dept);
        req.getRequestDispatcher("/pages/system/dept/add.jsp").forward(req,resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        Dept dept = BeanUtil.fillBean(req, Dept.class);
        deptService.update(dept);

        findAll(req,resp);
    }
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String ids = req.getParameter("id");
        deptService.delete(ids);

        findAll(req,resp);
    }



}
